using System;
using System.Linq;
using ContactCenter.Core.ObjectModel;

namespace ContactCenter.Core.Common
{
    /// <summary>
    /// Execute all task in sequence
    /// </summary>
    public static class TaskExecutor
    {
        public static TConf Execute<TConf>(params IConfigurationTask<TConf>[] tasks)
            where TConf : class, new()
        {
            return Execute(() => new TConf(), tasks);
        }

        public static TConf Execute<TConf>(Func<TConf> factory, params IConfigurationTask<TConf>[] tasks)
            where TConf : class, new()
        {
            TConf conf = factory();

            return tasks == null
                       ? conf
                       : tasks.Aggregate(conf,
                                         (current, task) => task.CanConfigure() 
                                             ? task.Configure(current) : current);
        }
    }
}